package com.reggie.background.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.background.common.R;
import com.reggie.background.common.ThreadLocalUtils;
import com.reggie.background.dto.OrdersDto;
import com.reggie.background.entity.OrderDetail;
import com.reggie.background.entity.Orders;
import com.reggie.background.service.OrderDetailService;
import com.reggie.background.service.OrdersService;
import com.reggie.background.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        Boolean result = ordersService.saveOrder(orders);
        if (result) {
            return R.success("已成功下单，请等待派送！");
        }
        return R.error("下单失败！");
    }
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userpage(int page, int pageSize){
        //根据分页查询订单
        Page<Orders> pageInfo=new Page<Orders>(page,pageSize);
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,ThreadLocalUtils.getThreadLocalValue());
        ordersService.page(pageInfo,qw);
        //根据分页中的订单id查询订单详细表并构建前端模型
        List<OrdersDto> collect = pageInfo.getRecords().stream().map(item -> {
            //查询订单详细表
            LambdaQueryWrapper<OrderDetail> od = new LambdaQueryWrapper<OrderDetail>();
            od.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> list = orderDetailService.list(od);
            //构建前端模型dao
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(list);
            ordersDto.setSumNum(list.size());
            return ordersDto;
        }).collect(Collectors.toList());
        //重新构建前端模型分页
        Page<OrdersDto> result=new Page<OrdersDto>();
        BeanUtils.copyProperties(pageInfo,result,"records");
        result.setRecords(collect);
        return R.success(result);
    }

}
